<?php

class systemBase {
	private $bgModulesData = array();
	private $lsError;
	private $lsInfo;

	public $csModuleName;
	public $Model;
	public $Smarty;
	public $csTemplateAction;
	public $Debug;

	public function __construct($lsModuleName) {
		global $_config;
		$this->csModuleName = $lsModuleName;
		/* nacteni modelu pro controller */
		if($_config["connection"]["enable"]) {
	        if(@include_once("./app/model/M".$this->csModuleName.".php")) {
	            $lsClassName = "M".$this->csModuleName."Class";
	            $this->Model = new $lsClassName;
	        }
	    }

		/* nacteni smarty */
		$this->Smarty = new Smarty;
		//$smarty->force_compile = true;
		$this->Smarty->debugging = false;
		$this->Smarty->caching = false;
		$this->Smarty->cache_lifetime = 0;
		$this->Smarty->setTemplateDir('./app/application');

		/* nacteni debugu */
		$this->Debug = new systemDebug($_config["debug"]["enable"], "debug.txt");
                
        /* Nastaveni erroru a info do template */
		$this->Smarty->assign("_info", $this->lsInfo);
        $this->Smarty->assign("_session", $_SESSION);

        /* smazat error a info v session */
        $this->deleteSessionError();
        $this->deleteSessionInfo();
                
		/* zpracovani akci */
		$lsAction = getGet("action");
		if(empty($lsAction)) {
			$lsAction = "default"; // defaultni akce modulu
		}
		$lsFunctionName = "action".$lsAction;
		$this->$lsFunctionName();
                
        $this->Smarty->assign("error", $this->lsError);
                
		/* moduly na pozadi */
		if($_config["backgroundmodule"]["active"]) {
			foreach ($_config["backgroundmodule"]["modules"] as $lsModuleName) {
				$bgModulesData[$lsModuleName] = $this->RunBackgroundModule($lsModuleName);
			}
			$this->Smarty->assign("BackgroundModulesData", $bgModulesData);
		}

		/* nacteni template */
		$this->setBaseVariables();
		if(empty($this->csTemplateAction)) {
			$this->csTemplateAction = $lsAction;
		}
		$this->Smarty->assign("content", "T".$this->csModuleName."_".$this->csTemplateAction.".tpl");
		$this->display();
    }

    public function display() {
        $this->Smarty->display("index.tpl");
    }

	private function setBaseVariables() {
		global $_config;
		$this->Smarty->assign("PATH_ROOT", $_config["path"]["root"]);
		$this->Smarty->assign("PATH_IMG", $_config["path"]["img"]);
		$this->Smarty->assign("PATH_JS", $_config["path"]["js"]);
	}

	private function RunBackgroundModule($isModuleName) {
		try{
			$lsModuleName = "B".$isModuleName;
			require "./app/controller/background/".$lsModuleName.".php";
			$lrBGModule = new $lsModuleName($isModuleName);
			return $lrBGModule->Run();
		}
		catch (Exception $e) {
			$this->addError("Exception: ".$e->getMessage());
		}
	}

	private function loadClass($isClassName) {
		try{
			require "./app/controller/".$isClassName.".php";
			$lrModules[$isClassName] = new $isClassName($isClassName);
		}
		catch (Exception $e) {
			$this->addError("Exception: ".$e->getMessage());
		}

	}

	public function addError($isText, $lbNewLine = true) {
		if(empty($isText)) {
			return;
		}
		if($lbNewLine) {
			$lsNewLine = "<br />";
		} else {
			$lsNewLine = "";
		}
		//
		$this->lsError = $this->lsError.$isText.$lsNewLine;
	}

	public function getError() {
		return $this->lsError;
	}

	// pokued nastala nejaka chyba
	public function IfError() {
		if(empty($this->lsError)) {
			return FALSE;
		} else {
			return TRUE;
		}
	}

	public function setError($isError) {
		$this->lsError = $isError;
	}

	public function addInfo($isText) {
		$this->lsInfo = $this->lsInfo.$isText."<br />";
	}

	public function actionDefault() {

	}
        
    public function getSessionError($lbDeleteError = true) {
        $lsError = getSession("Error");
        if($lbDeleteError) {
            deleteSession("Error");
        }
        return $lsError;
    }
    
    public function setSessionError($isText) {
        setSession("Error", $isText);
    }
    
    public function deleteSessionError() {
        deleteSession("Error");
    }

    public function setSessionInfo($isText) {
        setSession("Info", $isText);
    }
    
    public function deleteSessionInfo() {
        deleteSession("Info");
    }


	public function viewDetail() {

	}

	public function loginRequired($inLevel) {
		if(isLogged()) {
			$lrLogin = getSession("Login");
			if($inLevel > $lrLogin["level"]) {
				$this->AddError("Nedostatecna opravneni!");
				return FALSE;
			}
			return TRUE;
		} else {
			redirect(PATH_ROOT."?module=Auth&action=login");
		}
	}
    
    public function uploadFile($lrFile, $isFileType = "ALL", $lsPath = "upload/", $lnMaxFileSize = 5000000, $isFileName = null, &$orErrors = null) {
        //
        if(nvl($lrFile["size"],0) < 1) {
            return;
        }
        //
        if(empty($isFileName)) {
            $lsFileName = RandomString(8)."_".$lrFile["name"];
        } else {
            $lsFileName = RandomString(8)."_".$isFileName;
        }
        //
        $lsTemp = explode(".", $lrFile["name"]);
        $lsExtension = strtolower(end($lsTemp));
        // kontrola na spravny typ souboru
        if($isFileType == "IMAGE") {
            $lrAllowedExts = array("gif", "jpeg", "jpg", "png");
            if(!in_array($lrFile["type"], array("image/gif", "image/jpeg", "image/jpg", "image/pjpeg", "image/x-png", "image/png"))) {
                $this->addError("Soubor ".$lrFile["name"]." - Nejedná se o obrázek");
            }
        }
        // kontrola na spravnou velikost
        if($lrFile["size"] > $lnMaxFileSize) {
            $lnSizeMB = ($lnMaxFileSize / 1024)/1024;
            $this->addError("Soubor ".$lrFile["name"]." překročil povolenou velikost ".$lnSizeMB."MB");
        }
        // spravna koncovka souboru
        if($isFileType != "ALL") {
            if(!in_array($lsExtension, $lrAllowedExts)) {
                $this->addError("Soubor ".$lrFile["name"]." nemá správný typ: ".implode(", ", $lrAllowedExts));
            }
        }
        // vnitrni problem
        if ($lrFile["error"] > 0) {
            $this->addError($lrFile["error"]);
        }
        // ulozime soubor
        if(!$this->IfError()) {
            $lbFileExists = true;
            while($lbFileExists) {
                if (file_exists($lsPath . $lsFileName)) {
                  $lsFileName = RandomString(3).$lsFileName;
                } else {
                  $lbFileExists = false;
                }
            }
            move_uploaded_file($lrFile["tmp_name"], $lsPath.$lsFileName);
        }
        return $lsPath.$lsFileName;
    }

}
